<?php
class ActListsController extends AppController {
    var $pageTitle = 'Aktifitas Harian';
    
    function index() {
        $this->paginate['ActList']['order'] = array(
            'ActList.activity_date' => 'DESC',
            'ActList.id' => 'DESC'
        );
        parent::index();
    }
    
    function verify() {
        $this->set('title_for_layout', 'Aktifitas Harian Yang Perlu Diverifikasi');
        $this->paginate['ActList']['order'] = array(
            'ActList.activity_date' => 'DESC',
            'ActList.id' => 'DESC',
            
        );
        $_verified_positions = $this->ActList->CreatedBy->Position->children($this->Auth->user('position_id'), true);
        $__verified_positions = array();
        foreach ($_verified_positions as $_vp ) {
            $__verified_positions[ $_vp['Position']['id'] ] = $_vp['Position']['id'];
        }
        $_verified_users = $this->ActList->CreatedBy->find('all', array(
            'conditions' => array('CreatedBy.position_id' => $__verified_positions),
            'fields' => 'id', 'recursive' => -1
        ));
        $verified_users = array();
        foreach ($_verified_users as $_vu) {
            $verified_users[$_vu['CreatedBy']['id']] = $_vu['CreatedBy']['id'];
        }
        $condition = array(
            'ActList.created_by' => $verified_users
        );
        
        // filter by field passed in tablegrid
        $str_fl = '';
        if ( isset($this->params['url']['search']) && $this->params['url']['search'] == 'Search' ) {
            App::import('Sanitize');
            $filtered_link   = array();
            $filtered_link[] = '?search=Search';
            
            foreach ( $this->params['url'] as $param => $value ) {
                if ( !empty($value) && $param != 'url' && $param != 'search' && $param != 'ref') {
                    $filtered_link[] = $param . "=" . $value;
                    $this->set($param . "Value", $value);
                    $like = str_replace('*', '%', Sanitize::paranoid($value, array('*', ' ', '-')));
                    $condition[$this->modelName.".$param LIKE"] = $like;
                }
            }
            
            if (!empty($filtered_link)) {
                $str_fl = implode("&", $filtered_link);
            }
        }
        $this->set('str_fl', $str_fl);
        $this->set('records', $this->paginate($condition));
        
        // disable add and edit
        $module_permission['operations'] = array(
            'add' => false, 'delete' => false, 'print' => false, 'csv' => false, 'pdf' => false,
            'edit' => true
        );
        $this->set('module_permission', $module_permission);
        
        $this->set('formgrid', Helper::url('delete_rows'));
    }

    function add() {
        // cek apakah hari ini sudah ada aktifitas
        $exists = $this->ActList->find('count', array(
            'conditions' => array(
                'created_by' => $this->Auth->user('id'),
                'activity_date' => date('Y-m-d')
            ),
            'recursive' => -1
        ));
        
        if ( !$exists ) {
            $this->__setAdditionals();
            $this->__saving();
        } else {
            $this->Session->setFlash(
                'Sudah ada aktifitas yang diinput untuk hari ini, silahkan edit data tersebut jika ada perubahan.',
                'error'
            );
			$this->__redirect();
        }
	}
    
    function edit($id = null) {
        $action = 'index';
        if ( isset($this->params['url']['verify']) && $this->params['url']['verify'] ) {
            $action = 'verify';
        }
        
        if (!$id) {
            $this->Session->setFlash(__('Invalid parameter', true), 'error');
			$this->__redirect($action);
        }
		$this->set('id', $id);
        
        // first check wether user is a verificator or real user
        $this->ActList->Behaviors->attach('Containable');
        $user = $this->ActList->find('first', array(
            'conditions' => array('ActList.id' => $id), 'fields' => array('activity_date', 'verified_by', 'created_by', 'absent'),
            'contain' => array(
                'CreatedBy' => array(
                    'fields' => array('name', 'position_id')
                )
            )
        ));
        $verified_by = '';
        if ( isset($user['ActList']['created_by']) ) {
            $user_id = $user['ActList']['created_by'];
            $position_id = $user['CreatedBy']['position_id'];
            $name = $user['CreatedBy']['name'];
            
            $activity_date = $user['ActList']['activity_date'];
            $this->set('activity_date', $activity_date);
            
            $absent = $user['ActList']['absent'];
            $this->set('absent', $absent);
            
            $verified_by = $user['ActList']['verified_by'];
        } else {
            $this->Session->setFlash(__('Invalid parameter', true), 'error');
			$this->__redirect($action);
        }
        
        $this->__setAdditionals(1, $id, $user_id, $name, $position_id, $verified_by);
        $this->__saving(1, $id, $user_id, $position_id);
        
		if (empty($this->data)) {
			$this->data = $this->ActList->find('first', array(
                'conditions' => array('ActList.id' => $id)
            ));
            
            if (!$this->data) {
                $this->Session->setFlash(__('Invalid parameter', true), 'error');
                $this->__redirect($action);
            }
		} else {
            $this->data[$this->modelName]['id'] = $id;
        }
    }
    
    function __saving($edit = false, $id = null, $user_id = null, $position_id = null) {
        if ( !empty($this->data) ) {
            // action to be redirected to
            // when operation failed or succeed
            $action = 'index';
            if ( isset($this->params['url']['verify']) && $this->params['url']['verify'] ) {
                $action = 'verify';
            }
            
			$messageFlashSuccess = (isset($this->niceName) ? $this->niceName : $this->modelName) .
                                   ' ' . __('successfully added', true);
			$messageFlashError = (isset($this->niceName) ? $this->niceName : $this->modelName) .
                                 ' ' . __('cannot add this new record. Please fix the errors mentioned belows', true);
            if ( $edit ) {
                $messageFlashSuccess = (isset($this->niceName) ? $this->niceName : $this->modelName) .
                                       ' ' . __("successcully edited", true);
                $messageFlashError = (isset($this->niceName) ? $this->niceName : $this->modelName) .
                                     ' ' . __("cannot save this modification. Please fix the errors mentioned belows", true);
            }
            
            if ( $edit ) {
                $this->ActList->id = $id;
                $not_user = ($this->Auth->user('position_id') != $position_id) ? true : false;
                
                if ($not_user) {
                    $this->data['ActList']['verified'] = date('Y-m-d H:i:s');
                    $this->data['ActList']['verified_by'] = $this->Auth->user('position_id');
                }
            } else {
                $verificator = $this->ActList->getVerificator( $this->Auth->user('id') );
                $this->data['ActList']['activity_date'] = date('Y-m-d');
                $this->data['ActList']['verified_by'] = $verificator['id'];
                $this->ActList->create();
            }
            $lists = $this->data;
            
			if ($this->ActList->save($this->data)) {
                // on editing we need to delete all
                // act_list_activity and descriptions
                // whose act_list_id is $id
                if ( $edit && $id ) {
                    // get created_by, since
                    // we are delete all children
                    $created_by = $this->ActList->find('first', array(
                        'conditions' => array(
                            'ActList.id' => $id
                        ),
                        'fields' => array('ActList.created_by'),
                        'recursive' => -1
                    ));
                    $created_by = $created_by['ActList']['created_by'];
                    
                    $this->ActList->ActListActivity->deleteAll(
                        array('ActListActivity.act_list_id' => $id),
                        true,
                        true
                    );
                }
				
                // set list_id, created_by and modified_by
                foreach ( $this->data['ActList']['ActListActivity'] as $key => $bd ) {
                    $this->data['ActList']['ActListActivity'][$key]['act_list_id'] = $this->ActList->id;
                    
                    // save act_list_activity one by one
                    $this->ActList->ActListActivity->create();
                    if ( $this->ActList->ActListActivity->save($this->data['ActList']['ActListActivity'][$key]) ) {
                        // set act_list_activity_id, created_by or modified_by
                        // on ActListActivityDescription
                        foreach ( $this->data['ActList']['ActListActivity']
                            [$key]['ActListActivityDescription'] as $key2 => $bdd ) {
                                
                            $this->data['ActList']['ActListActivity']
                                [$key]['ActListActivityDescription']
                                [$key2]['act_list_activity_id'] = $this->ActList->ActListActivity->id;
                        }
                        
                        // save all description per each act_list_activity_id
                        $this->ActList->ActListActivity->ActListActivityDescription->create();
                        if  ( $this->ActList->ActListActivity->ActListActivityDescription->saveAll(
                              $this->data['ActList']['ActListActivity'][$key]['ActListActivityDescription']) ) {
                            // oke
                            
                        } else { // failed savingAll description
                            $this->set('lists', $lists['ActList']);
                            $this->Session->setFlash($messageFlashError, 'error');
                        }
                    // eof saving detail
                    } else { // failed saving list_activities
                        $this->set('lists', $lists['ActList']);
                        $this->Session->setFlash($messageFlashError, 'error');
                    }
                } // eof set list_id
                $this->Session->setFlash( $messageFlashSuccess, 'success');
                $this->__redirect($action);
			} else { // failed saving lists
                $this->set('lists', $lists['ActList']);
                $this->Session->setFlash($messageFlashError, 'error');
			}
		}
    }
    
    function __setAdditionals($edit = false, $id = null, $user_id = null, $name = null, $position_id = null, $verified_by = '') {
        // action to be redirected to
        // when operation failed or succeed
        $action = 'index';
        if ( isset($this->params['url']['verify']) && $this->params['url']['verify'] ) {
            $action = 'verify';
            $this->set('action_suffix', $action);
        }
        
        // check if user is a real user or verificator
        // just on edit
        $not_user = false;
        if ( $edit && $id ) {
            $not_user = ($this->Auth->user('position_id') != $position_id) ? true : false;
        }
        $this->set('not_user', $not_user);
        
        $position_id_condition = $this->Auth->user('position_id');
        $user_id_condition = $this->Auth->user('id');
        $creator_name = $this->Auth->user('name');
        // assumed as verificator or admin
        if ( $edit && $not_user ) {
            $position_id_condition = $position_id;
            $user_id_condition = $user_id;
            $creator_name = $name;
        }
        // absent options
        $this->set('absent_options', $this->ActList->generateAbsentOptions());
        // creator name
        $this->set('creator_name', $creator_name);
        
        // my position
        $my_position = $this->ActList->CreatedBy->Position->find('first', array(
            'conditions' => array('id' => $position_id_condition),
            'recursive' => -1, 'fields' => array('name')
        ));
        $this->set('my_position', $my_position['Position']['name']);
        
        // verificator position
        if ( !empty($verified_by) ) {
            $verificator_position = $this->ActList->CreatedBy->Position->find('first', array(
                'fields' => array('id', 'name'), 'recursive' => -1, 'conditions' => array('id' => $verified_by)
            ));
            $verificator = $verificator_position['Position'];
            $this->set('verificator_position', $verificator_position['Position']['name']);
            $this->set('verificator_position_id', $verified_by);
        } else {
            $verificator = $this->ActList->getVerificator( $user_id_condition );
            $this->set('verificator_position', $verificator['name']);
            $this->set('verificator_position_id', $verificator['id']);
        }
        
        // if not an creator nor an admin nor a verificator
        if ( $edit && $not_user && $this->Auth->user('group_id') != 1 && 
             $verificator['id'] != $this->Auth->user('position_id'))
        {
            $this->Session->setFlash(__('Anda tidak punya akses untuk melihat', true), 'error');
			$this->__redirect($action);
        }
        
        // kegiatan
        $activities = $this->ActList->ActListActivity->Activity->find('list', array(
            'conditions' => array(
                'Activity.position_id' => $position_id_condition
            )
        ));
        $this->set('activities', $activities);
        
        if ( $edit ) {
            // get act_lists
            $this->ActList->Behaviors->attach('Containable');
            $lists = $this->ActList->find('first', array(
                'conditions' => array(
                    'ActList.id' => $id
                ),
                'contain' => array(
                    'ActListActivity' => array(
                        'ActListActivityDescription' => array(
                            'order' => 'ActListActivityDescription.id ASC'
                        ),
                        'order' => 'ActListActivity.id ASC'
                    )
                ),
                'order' => 'ActList.id ASC'
            ));
            $this->set('lists', $lists);
        }
    }
    
    function report_per_day() {
        $show_form = true;
        if ( isset($this->data['ActList']['date']) && !empty($this->data['ActList']['date']) ) {
            $show_form = false;
            Configure::write('debug', 0);
            $this->layout = 'printhtml';
            $date = $this->data['ActList']['date']['year'] . '-' . $this->data['ActList']['date']['month'] . '-' .
                    $this->data['ActList']['date']['day'];
            $this->set('date', $date);
            $this->ActList->Behaviors->attach('Containable');
            $records = $this->ActList->find('all', array(
                'conditions' => array(
                    'ActList.activity_date' => $date
                ),
                'contain' => array(
                    'CreatedBy' => array(
                        'fields' => array('name', 'nip'),
                        'Position' => array(
                            'fields' => array('name', 'parent_id')
                        ),
                        'UnitCode' => array(
                            'fields' => array('name')
                        )
                    ),
                    'ActListActivity' => array(
                        'Activity' => array(
                            'fields' => array('name')
                        ),
                        'ActListActivityDescription' => array(
                            'fields' => array('description', 'assignment_no', 'verified')
                        )
                    )
                )
            ));
            
            $positions = $this->ActList->VerifiedBy->Position->find('list');
            $absent_options = $this->ActList->generateAbsentOptions();
            $insentive_cutoff = $this->Session->read('Site.potongan_insentif_tk');
            $insentive_per_item = $this->Session->read('Site.kemampuan_insentif');
            
            foreach ($records as $key => $record) {
                $records[$key]['CreatedBy']['unit_code_name'] = $record['CreatedBy']['UnitCode']['name'];
                $records[$key]['CreatedBy']['position_name'] = $record['CreatedBy']['Position']['name'];
                $records[$key]['ActList']['activity'] = '';
                $records[$key]['ActList']['verificator'] = '';
                if ( isset($positions[$records[$key]['ActList']['verified_by']]) ) {
                    $records[$key]['ActList']['verificator'] = $positions[$records[$key]['ActList']['verified_by']];
                }
                if ( !empty($record['ActList']['verified']) ) {
                    $records[$key]['ActList']['verified'] = date('d/m/Y H:i:s', strtotime($record['ActList']['verified']));
                }
                
                // insentive, cut-off & performance
                $records[$key]['ActList']['insentive'] = 0;
                $records[$key]['ActList']['insentive_cutoff'] = 0;
                $records[$key]['ActList']['performance'] = 0;
                if ( $records[$key]['ActList']['absent'] == 1 || // izin
                     $records[$key]['ActList']['absent'] == 2 || // sakit
                     $records[$key]['ActList']['absent'] == 3 || // cuti
                     $records[$key]['ActList']['absent'] == 4 ) // tidak kerja
                {
                
                    $records[$key]['ActList']['insentive_cutoff'] = $insentive_cutoff;
                } else if ( $records[$key]['ActList']['absent'] == 5 || // diklat
                            $records[$key]['ActList']['absent'] == 7 )  // dinas luar
                {
                    $records[$key]['ActList']['performance'] = 100;
                }
                
                // absent nice name
                $records[$key]['ActList']['absent'] = $absent_options[$records[$key]['ActList']['absent']];
                
                if ( !empty($record['ActListActivity']) ) {
                    $records[$key]['ActList']['activity'] = '<ol>';
                    foreach ( $record['ActListActivity'] as $key2 => $activity ) {
                        $records[$key]['ActList']['activity'] .= '<li>' . $activity['Activity']['name'];
                        
                        if ( !empty($activity['ActListActivityDescription']) ) {
                            $records[$key]['ActList']['activity'] .= '<ol>';
                            foreach ( $activity['ActListActivityDescription'] as $key3 => $desc ) {
                                if ( !empty($desc['description']) ) {
                                    if ( !empty($desc['assignment_no']) ) {
                                        $desc['description'] .= ' &mdash; No surat tugas ' . $desc['assignment_no'];
                                    }
                                    if ( $desc['verified'] ) {
                                        $desc['description'] .= ' &radic;';
                                        
                                        if ( $records[$key]['ActList']['performance'] < 100 ) {
                                            $records[$key]['ActList']['performance'] += 20;
                                        }
                                    }
                                    $records[$key]['ActList']['activity'] .=  '<li>' . $desc['description'] . '</li>';
                                }
                            }
                            $records[$key]['ActList']['activity'] .= '</ol>';
                        }
                        $records[$key]['ActList']['activity'] .= '</li>';
                    }
                    $records[$key]['ActList']['activity'] .= '</ol>';
                }
                
                // insentive that user gets
                if ( $records[$key]['ActList']['performance'] > 0 ) {
                    $records[$key]['ActList']['insentive'] = ($records[$key]['ActList']['performance'] / 20) * $insentive_per_item;
                }
                // insentive cut-off that user gets
                if ( $records[$key]['ActList']['insentive_cutoff'] == $insentive_cutoff ) {
                    $records[$key]['ActList']['insentive'] = 0;
                    $records[$key]['ActList']['performance'] = 0;
                }
            }
            $this->set('records', $records);
        }
        
        $this->set('show_form', $show_form);
    }
    
    function report_per_month() {
        $show_form = true;
        $users = $this->ActList->CreatedBy->find('list', array(
            'fields' => array('id', 'name'),
            'order' => 'name ASC',
            'recursive' => -1
        ));
        $this->set('users', $users);
        
        if ( !empty($this->data['month']['month']) && !empty($this->data['year']['year']) ) {
            $show_form = false;
            Configure::write('debug', 0);
            $this->layout = 'printhtml';
            $min_date = $this->data['year']['year'] . '-' . $this->data['month']['month'] . '-01';
            $max_date = $this->data['year']['year'] . '-' . $this->data['month']['month'] . '-31';
            $date = $this->getMonthName($this->data['month']['month']) . ' ' . $this->data['year']['year'];
            $this->set('date', $date);
            $conditions = array(
                'ActList.activity_date >=' => $min_date,
                'ActList.activity_date <=' => $max_date
            );
            if ( isset($this->data['ActList']['user']) && !empty($this->data['ActList']['user']) ) {
                $conditions['ActList.created_by'] = $this->data['ActList']['user'];
                $this->ActList->CreatedBy->Behaviors->attach('Containable');
                $user = $this->ActList->CreatedBy->find('first', array(
                    'fields' => array('CreatedBy.name', 'CreatedBy.nip'),
                    'conditions' => array(
                        'CreatedBy.id' => $this->data['ActList']['user']
                    ),
                    'contain' => array(
                        'UnitCode' => array(
                            'fields' => array('name')
                        ),
                        'Position' => array(
                            'fields' => array('name')
                        )
                    )
                ));
                if ( !empty($user) ) {
                    $this->set('user', $user);
                }
            }
            
            $this->ActList->Behaviors->attach('Containable');
            $records = $this->ActList->find('all', array(
                'conditions' => $conditions,
                'contain' => array(
                    'CreatedBy' => array(
                        'fields' => array('name', 'nip'),
                        'Position' => array(
                            'fields' => array('name', 'parent_id')
                        ),
                        'UnitCode' => array(
                            'fields' => array('name')
                        )
                    ),
                    'ActListActivity' => array(
                        'Activity' => array(
                            'fields' => array('name')
                        ),
                        'ActListActivityDescription' => array(
                            'fields' => array('description', 'assignment_no', 'verified')
                        )
                    )
                )
            ));
            
            // options var
            $positions = $this->ActList->VerifiedBy->Position->find('list');
            $absent_options = $this->ActList->generateAbsentOptions();
            $this->set('absent_options', $absent_options);
            
            // insentive var from session
            $insentive_cutoff = $this->Session->read('Site.potongan_insentif_tk');
            $insentive_per_item = $this->Session->read('Site.kemampuan_insentif');
            
            // total insentive and performance
            $total_insentive = 0;
            $total_perfomance = 0;
            
            // total per absent type
            $total_hadir = $absent_options;
            foreach ( $total_hadir as $thk => $thv ) {
                $total_hadir[ $thk ] = 0;
            }
            
            foreach ($records as $key => $record) {
                $records[$key]['CreatedBy']['unit_code_name'] = $record['CreatedBy']['UnitCode']['name'];
                $records[$key]['CreatedBy']['position_name'] = $record['CreatedBy']['Position']['name'];
                $records[$key]['ActList']['activity'] = '';
                $records[$key]['ActList']['verificator'] = '';
                if ( isset($positions[$records[$key]['ActList']['verified_by']]) ) {
                    $records[$key]['ActList']['verificator'] = $positions[$records[$key]['ActList']['verified_by']];
                }
                if ( !empty($record['ActList']['verified']) ) {
                    $records[$key]['ActList']['verified'] = date('d/m/Y H:i:s', strtotime($record['ActList']['verified']));
                }
                
                // insentive, cut-off & performance
                $records[$key]['ActList']['insentive'] = 0;
                $records[$key]['ActList']['insentive_cutoff'] = 0;
                $records[$key]['ActList']['performance'] = 0;
                if ( $records[$key]['ActList']['absent'] == 1 || // izin
                     $records[$key]['ActList']['absent'] == 2 || // sakit
                     $records[$key]['ActList']['absent'] == 3 || // cuti
                     $records[$key]['ActList']['absent'] == 4 ) // tidak kerja
                {
                
                    $records[$key]['ActList']['insentive_cutoff'] = $insentive_cutoff;
                } else if ( $records[$key]['ActList']['absent'] == 5 || // diklat
                            $records[$key]['ActList']['absent'] == 7 ) // dinas luar
                {
                    $records[$key]['ActList']['performance'] = 100;
                }
                
                // total absent per type
                // NOTE : need to be above the overriden of absent nice name below
                $total_hadir[ $records[$key]['ActList']['absent'] ]++;
                
                // absent nice name
                $records[$key]['ActList']['absent'] = $absent_options[$records[$key]['ActList']['absent']];
                
                if ( !empty($record['ActListActivity']) ) {
                    $records[$key]['ActList']['activity'] = '<ol>';
                    foreach ( $record['ActListActivity'] as $key2 => $activity ) {
                        $records[$key]['ActList']['activity'] .= '<li>' . $activity['Activity']['name'];
                        
                        if ( !empty($activity['ActListActivityDescription']) ) {
                            $records[$key]['ActList']['activity'] .= '<ol>';
                            foreach ( $activity['ActListActivityDescription'] as $key3 => $desc ) {
                                if ( !empty($desc['description']) ) {
                                    if ( !empty($desc['assignment_no']) ) {
                                        $desc['description'] .= ' &mdash; No surat tugas ' . $desc['assignment_no'];
                                    }
                                    if ( $desc['verified'] ) {
                                        $desc['description'] .= ' &radic;';
                                        
                                        if ( $records[$key]['ActList']['performance'] < 100 ) {
                                            $records[$key]['ActList']['performance'] += 20;
                                        }
                                    }
                                    $records[$key]['ActList']['activity'] .=  '<li>' . $desc['description'] . '</li>';
                                }
                            }
                            $records[$key]['ActList']['activity'] .= '</ol>';
                        }
                        $records[$key]['ActList']['activity'] .= '</li>';
                    }
                    $records[$key]['ActList']['activity'] .= '</ol>';
                }
                
                // insentive that user gets
                if ( $records[$key]['ActList']['performance'] > 0 ) {
                    $records[$key]['ActList']['insentive'] = ($records[$key]['ActList']['performance'] / 20) * $insentive_per_item;
                }
                // insentive cut-off that user gets
                if ( $records[$key]['ActList']['insentive_cutoff'] == $insentive_cutoff ) {
                    $records[$key]['ActList']['insentive'] = 0;
                    $records[$key]['ActList']['performance'] = 0;
                }
                
                // accumulate total for insentive and performance
                $total_insentive += $records[$key]['ActList']['insentive'];
                $total_perfomance += $records[$key]['ActList']['performance'];
            }
            $this->set('records', $records);
            $this->set('total_insentive', $total_insentive);
            $this->set('total_perfomance', $total_perfomance / count($records));
            $this->set('total_hadir', $total_hadir);
        }
        
        $this->set('show_form', $show_form);
    }
    
    function report_per_month_summary() {
        $show_form = true;
        $unit_codes = $this->ActList->CreatedBy->UnitCode->find('list', array(
            'fields' => array('id', 'name'),
            'order' => 'name ASC',
            'recursive' => -1
        ));
        $this->set('unit_codes', $unit_codes);
        
        if ( !empty($this->data['month']['month']) && !empty($this->data['year']['year']) ) {
            $show_form = false;
            Configure::write('debug', 0);
            $this->layout = 'printhtml';
            $min_date = $this->data['year']['year'] . '-' . $this->data['month']['month'] . '-01';
            $max_date = $this->data['year']['year'] . '-' . $this->data['month']['month'] . '-31';
            $date = $this->getMonthName($this->data['month']['month']) . ' ' . $this->data['year']['year'];
            $this->set('date', $date);
            $conditions = array(
                'ActList.activity_date >=' => $min_date,
                'ActList.activity_date <=' => $max_date
            );
            
            // get unit_code name from selected unit_code_id
            $unit_code = $this->ActList->CreatedBy->UnitCode->find('first', array(
                'fields' => array('UnitCode.name'),
                'conditions' => array('UnitCode.id' => $this->data['ActList']['unit_code']),
                'recursive' => -1
            ));
            if ( !empty($unit_code) ) {
                $this->set('unit_code', $unit_code['UnitCode']['name']);
            }
            
            // get users from selected unit_code
            $users = array();
            $_users = $this->ActList->CreatedBy->find('all', array(
                'fields' => array('CreatedBy.id'),
                'conditions' => array(
                    'CreatedBy.unit_code_id' => $this->data['ActList']['unit_code']
                ),
                'recursive' => -1
            ));
            foreach ( $_users as $_user ) {
                $users[ $_user['CreatedBy']['id'] ] = $_user['CreatedBy']['id'];
            }
            if ( !empty($users) ) {
                $conditions['ActList.created_by'] = $users;
            }
            
            $this->ActList->Behaviors->attach('Containable');
            $records = $this->ActList->find('all', array(
                'conditions' => $conditions,
                'contain' => array(
                    'CreatedBy' => array(
                        'fields' => array('id', 'name', 'nip'),
                        'Position' => array(
                            'fields' => array('name', 'parent_id')
                        ),
                        'UnitCode' => array(
                            'fields' => array('name')
                        )
                    ),
                    'ActListActivity' => array(
                        'Activity' => array(
                            'fields' => array('name')
                        ),
                        'ActListActivityDescription' => array(
                            'fields' => array('description', 'assignment_no', 'verified')
                        )
                    )
                )
            ));
            
            // options var
            $positions = $this->ActList->VerifiedBy->Position->find('list');
            $absent_options = $this->ActList->generateAbsentOptions();
            $this->set('absent_options', $absent_options);
            
            // insentive var from session
            $insentive_cutoff = $this->Session->read('Site.potongan_insentif_tk');
            $insentive_per_item = $this->Session->read('Site.kemampuan_insentif');
            
            // total insentive and performance per user
            $total_insentive = array();
            $total_perfomance = array();
            
            // total absent per user
            $total_hadir = array();
            
            // total day counted
            $total_day = array();
            
            foreach ($records as $key => $record) {
                $records[$key]['CreatedBy']['unit_code_name'] = $record['CreatedBy']['UnitCode']['name'];
                $records[$key]['CreatedBy']['position_name'] = $record['CreatedBy']['Position']['name'];
                $records[$key]['ActList']['activity'] = '';
                $records[$key]['ActList']['verificator'] = '';
                if ( isset($positions[$records[$key]['ActList']['verified_by']]) ) {
                    $records[$key]['ActList']['verificator'] = $positions[$records[$key]['ActList']['verified_by']];
                }
                if ( !empty($record['ActList']['verified']) ) {
                    $records[$key]['ActList']['verified'] = date('d/m/Y H:i:s', strtotime($record['ActList']['verified']));
                }
                
                // insentive, cut-off & performance
                $records[$key]['ActList']['insentive'] = 0;
                $records[$key]['ActList']['insentive_cutoff'] = 0;
                $records[$key]['ActList']['performance'] = 0;
                if ( $records[$key]['ActList']['absent'] == 1 || // izin
                     $records[$key]['ActList']['absent'] == 2 || // sakit
                     $records[$key]['ActList']['absent'] == 3 || // cuti
                     $records[$key]['ActList']['absent'] == 4 ) // tidak kerja
                {
                
                    $records[$key]['ActList']['insentive_cutoff'] = $insentive_cutoff;
                } else if ( $records[$key]['ActList']['absent'] == 5 || // diklat
                            $records[$key]['ActList']['absent'] == 7 ) // dinas luar
                {
                    $records[$key]['ActList']['performance'] = 100;
                }
                
                // total absent per user
                if ( !isset($total_hadir[ $record['CreatedBy']['id'] ]) ) {
                    $total_hadir[ $record['CreatedBy']['id'] ] = $absent_options;
                    foreach ( $total_hadir[ $record['CreatedBy']['id'] ] as $absent_key => $absent_val  ) {
                        $total_hadir[ $record['CreatedBy']['id'] ][ $absent_key ] = 0;
                    }
                    $total_day[ $record['CreatedBy']['id'] ] = 0;
                }
                $total_hadir[ $record['CreatedBy']['id'] ][ $record['ActList']['absent'] ]++;
                $total_day[ $record['CreatedBy']['id'] ]++;
                
                if ( !empty($record['ActListActivity']) ) {
                    foreach ( $record['ActListActivity'] as $key2 => $activity ) {
                        if ( !empty($activity['ActListActivityDescription']) ) {
                            $records[$key]['ActList']['activity'] .= '<ol>';
                            foreach ( $activity['ActListActivityDescription'] as $key3 => $desc ) {
                                if ( !empty($desc['description']) ) {
                                    if ( $desc['verified'] ) {
                                        if ( $records[$key]['ActList']['performance'] < 100 ) {
                                            $records[$key]['ActList']['performance'] += 20;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                
                // insentive that user gets
                if ( $records[$key]['ActList']['performance'] > 0 ) {
                    $records[$key]['ActList']['insentive'] = ($records[$key]['ActList']['performance'] / 20) * $insentive_per_item;
                }
                // insentive cut-off that user gets
                if ( $records[$key]['ActList']['insentive_cutoff'] == $insentive_cutoff ) {
                    $records[$key]['ActList']['insentive'] = 0;
                    $records[$key]['ActList']['performance'] = 0;
                }
                
                // accumulate total for insentive and performance
                // per user
                if ( !isset($total_insentive[ $record['CreatedBy']['id'] ]) ) {
                    $total_insentive[ $record['CreatedBy']['id'] ] = 0;
                }
                $total_insentive[$record['CreatedBy']['id']] += $records[$key]['ActList']['insentive'];
                if ( !isset($total_perfomance[ $record['CreatedBy']['id'] ]) ) {
                    $total_perfomance[ $record['CreatedBy']['id'] ] = 0;
                }
                $total_perfomance[$record['CreatedBy']['id']] += $records[$key]['ActList']['performance'];
            }
            
            // reformat records for this special report
            // grouped by user_id
            $record_grouped = array();
            $all_total_insentive = 0;
            $all_total_performance = 0;
            $all_total_absent = $absent_options;
            foreach ( $all_total_absent as $absent_key => $absent_val  ) {
                $all_total_absent[ $absent_key ] = 0;
            }
            foreach ( $records as $record ) {
                if ( !isset($record_grouped[ $record['CreatedBy']['id'] ]) ) {
                    $record_grouped[ $record['CreatedBy']['id'] ]['CreatedBy'] = $record['CreatedBy'];
                    $record_grouped[ $record['CreatedBy']['id'] ]['ActList'] = $record['ActList'];
                    $all_total_insentive += $total_insentive[$record['CreatedBy']['id']];
                    
                    // total absent
                    foreach ( $all_total_absent as $absent_key => $absent_val  ) {
                        $all_total_absent[ $absent_key ] += $total_hadir[$record['CreatedBy']['id']][$absent_key];
                    }
                    
                    // total performance
                    $record_grouped[ $record['CreatedBy']['id'] ]['ActList']['total_day'] = $total_day[$record['CreatedBy']['id']];
                    $record_grouped[ $record['CreatedBy']['id'] ]['ActList']['performance'] =
                        $total_perfomance[$record['CreatedBy']['id']] / $total_day[$record['CreatedBy']['id']];
                        $all_total_performance += $record_grouped[ $record['CreatedBy']['id'] ]['ActList']['performance'];
                }
                
                $record_grouped[ $record['CreatedBy']['id'] ]['ActList']['insentive'] = $total_insentive[$record['CreatedBy']['id']];
                
                    
                $record_grouped[ $record['CreatedBy']['id'] ]['ActList']['absent'] = $total_hadir[$record['CreatedBy']['id']];
            }
            
            $this->set('records', $record_grouped);
            $this->set('all_total_absent', $all_total_absent);
            $this->set('all_total_insentive', $all_total_insentive);
            $this->set('all_total_performance', $all_total_performance > 0 ? 
                ($all_total_performance / count($record_grouped)) :
                $all_total_performance
            );
        }
        
        $this->set('show_form', $show_form);
    }
}
?>
